<template>
	<div class="scale-container" :style="{ 'width': `${property.width}px` }">
		<div class="scale" :style="{ 'background': property.bgColor1 }">
			<div v-for="item in markList" class="mark" :style="`${property.direction == 1 ? 'left' : 'right'}: ${
	          (item / echartsOptionData.total_length) * property.width - (item > 999 ? 20 : item > 99 ? 14 : 6)
	        }px`">{{ item }}m</div>
		</div>
		<div class="progress-bar" :style="{
	        'background': `${property.bgColor2}`,
	        'width': `${(echartsOptionData.complete_length / echartsOptionData.total_length) * 100}%`,
	      }" :class="{ 'left-direction': property.direction == 1, 'right-direction': property.direction == 2 }"></div>
		<!-- 刻度线 -->
		<div v-for="item in markList" class="tick"
			:style="`${property.direction == 1 ? 'left' : 'right'}: ${(item / echartsOptionData.total_length) * 100}%`">
		</div>
		<el-tooltip :content="item.tooltps" raw-content placement="top" v-for="item in echartsOptionData.userList">
			<div class="icon" :style="`${property.direction == 1 ? 'left' : 'right'}: ${
	          property.direction == 1
	            ? (item.position / echartsOptionData.total_length) * property.width
	            : (item.position / echartsOptionData.total_length) * property.width - 16
	        }px`"></div>
		</el-tooltip>
	</div>
</template>
<script>
	import * as echarts from 'echarts'
	import chartBase from '@/mixin/chart-base.js';
	import emitComponentBase from '@/mixin/emit-component-base.js';
	import dataModel from '@/models/panel-config-data.js';
	import {
		checkNegative
	} from '@/utils/util';
	import {
		mapState
	} from 'vuex';
	import config from './config/config';
	// import { useChartBase } from '@/use-api/use-chart-base'


	export default {
		name: 'PersonnelPositioning',
		// components: {

		// },
		mixins: [chartBase, emitComponentBase],
		props: ['pareentId', 'widgetId', 'widgetInstanceId', 'widgetName', 'identifier', 'layout', 'w', 'h', 'Item'],
		data() {
			return {
				chart: null, // 存储echarts实例
				echartsOptionData: {
					'total_length': 1600,
					'complete_length': 640,
					'userList': [{
						name: '',
						position: '',
					}]
				},

				dataList: [{
						'total_length': 1600,
						'post': '采煤工',
						'name': '李四',
						'position': 166,
						'complete_length': 640,
					},
					{
						'total_length': 1600,
						'post': '采煤工',
						'name': '张三',
						'position': 50,
						'complete_length': 640,
					},
					{
						'total_length': 1600,
						'post': '运输队',
						'name': '王五',
						'position': 80,
						'complete_length': 640,
					},
					{
						'total_length': 1600,
						'post': '运输队',
						'name': 'aaa',
						'position': 255,
						'complete_length': 640,
					},
					{
						'total_length': 1600,
						'post': '运输队',
						'name': 'bbb',
						'position': 320,
						'complete_length': 640,
					},
					{
						'total_length': 1600,
						'post': '采煤司机',
						'name': 'ccc',
						'position': 640,
						'complete_length': 640,
					}
				],
				markList: []


			};
		},
		computed: {
			...mapState({}),
			property() {
				return this.config?.config?.property ?? {}
			}
		},
		watch: {

		},
		created() {
			this.orgConfig = config;
			this.config = JSON.parse(JSON.stringify(this.orgConfig));
			this.chartId = `${this.widgetInstanceId}_01`;

		},
		mounted() {
			if (window.isLocalEnv) {
				this.loadWidget();
			}
		},
		methods: {

			// 初始加载时 以及 编排面更改配置时 触发
			loadWidget(pageStatus) {
				this.pageStatus = pageStatus;
				this.updateConfigProperty();
				this.updateConfigData();
				if (window.isLocalEnv || this.emitComponentStatus) {
					this.updateParams(pageStatus);
					if (!this.isRealTime) {
						this.debounceGetData();
					}
				}
				this.afterLoadWidget();
				this.checkNegative(this.apiResult);
			},

			// 接收xvue发来的实时数据
			handleRealTimeCommunication(realTimeData) {
				if (this.config.config.property.isDebounce && this.isStopRealData) {
					return;
				}

				const result = this.getResult(realTimeData);
				if (this.isNoData || this.autoRefreshIsSameRes(result)) {
					this.isLoading = false;
					return;
				}
				const {
					data,
					property
				} = this.config.config;

				// api请求，拿到数据
				if (data.dataSourceType !== 'xMinerRedisRealTime') {
					this.getCorrectParams(this.params, data.dataSourceType); // 参数存入xvue，导出数据时使用
				}
				// this.apiResult = result;
				// this.lastParams = null;
				// this.sendDataToConfig(result);
				// const convertedData = convertData(result, property);
				// if (convertedData === -1) {
				//   this.$message.error(this.$demoi18n('view.dataSourceTypeErr'));
				//   this.setDataException();
				//   return;
				// }
				// this.generateChart(convertedData);
				// this.isLoading = false;
			},
			acceptEvtMsg(paramters, key, obj) {
				this.checkUpdateParams(obj);
			},
			checkUpdateParams(obj) {
				// 检查下是否和本组件有关
				const _obj = obj || {};
				let oo = {}
				let flag = false;
				for (const key in _obj) {
					if (key.indexOf(EMIT_PARAMS_OBJ) > -1) {
						const o = _obj[key];
						if (o.eventKey) {
							const event = this.config.events.find(e => e.type === 'in' && e.key === o.eventKey);
							if (event) {
								flag = true;
								oo = o
							}
							break;
						}
					}
				}
				if (flag) {
					// 和本组件有关再执行组件接收到事件后的相关操作
					console.log('_obj', _obj)
					console.log('oo', oo)

					this.isNoData = false;
					this.isLoading = true;
					this.autoRefresh();
					const alarm_id = oo?.parameters[oo?.keys[0]]
					let param = {
						code: 'alarm_id',
						value: alarm_id
					}
					let paramOo = [param]

					// api请求，拿到数据
					const {
						data
					} = this.config.config
					this.isLoading = true
					const method = `getChartData${data.dataSourceType}`;
					const trueParams = this.getCorrectParams(this.params, data.dataSourceType);
					trueParams = {
						...trueParams,
						params: paramOo,
					};

					dataModel[method](trueParams, data)
						.then(result => {
							this.echartsOptionData.length = 0
							this.echartsOptionData = result.data
							this.echartsOptionfunction(this.echartsOptionData)
						})
						.catch(err => {
							this.handleChartDataError(err);
						})
						.finally(() => {
							this.isLoading = false;
						});
				}
			},
			getChartData() {
				const {
					data,
					property
				} = this.config.config;

				// 如果dataSourceType为静态数据,把数据放到Vuex，发出事件，然后退出
				if (data.dataSourceType === 'staticData') {
					this.echartsOptionfunction(this.dataList)
					// 重置数据异常状态
					this.resetAbnormalType();
					return;
				}

				// api请求，拿到数据
				if (data.dataSourceType) {
					this.isNoData = false;
					this.isLoading = true;
					this.autoRefresh();
					const method = `getChartData${data.dataSourceType}`;
					const params = this.getCorrectParams(this.params, data.dataSourceType);
					dataModel[method](params, data)
						.then(result => {
						console.log('api接口数据',result)
							this.echartsOptionData.length = 0
							this.echartsOptionData = result
							this.echartsOptionfunction(this.echartsOptionData)

							// 重置数据异常状态
							this.resetAbnormalType();
							this.reportIfFieldsError(this.getParams()?.propertyMapping, result);
							if (this.autoRefreshIsSameRes(result)) {
								return;
							}

						})
						.catch(err => {
							this.handleChartDataError(err);
						})
						.finally(() => {
							this.isLoading = false;
						});
				} else {
					// 如果在用户面，则给提示
					if (this.$route.name === 'userHomePage') {
						this.$message({
							message: this.$demoi18n('view.dataSourceTypeEmpty'),
							type: 'warning',
						});
					}
				}
			},

			echartsOptionfunction(echartsData) {
				const {
					data
				} = this.config.config
				console.log('图表内', echartsData)
				// console.log('data', data)
				const userArr = []
				const tableData = data.tableData.slice(2)
				// console.log('tableData:', tableData)
				this.markList.length = 0
				for (
					let i = echartsData[0][data.tableData[0].field]; i > echartsData[0][data.tableData[1].field]; i = i -
					this.config.config.property.stepLength
				) {
					this.markList.push(i)
				}
				this.markList.push(echartsData[0][data.tableData[1].field])
				this.markList.push(0)
				// console.log('markList:', this.markList)
				echartsData.forEach((et) => {
					let field = ''
					let str = '<div>'
					tableData.forEach((item, index) => {
						if (index == tableData.length - 1) {
							if (item.name == '人员位置') {
								field = item.field
								str = str + item.name + ': ' + et[item.field] + 'm'
							} else {
								str = str + item.name + ': ' + et[item.field]
							}
						} else {
							if (item.name == '人员位置') {
								field = item.field
								str = str + item.name + ': ' + et[item.field] + 'm</br>'
							} else {
								str = str + item.name + ': ' + et[item.field] + '</br>'
							}
						}
					})
					str = str + '</div>'
					userArr.push({
						position: et[field],
						tooltps: str,
					})
				})
				console.log('userArr:', userArr)
				this.echartsOptionData = {
					'total_length': echartsData[0][data.tableData[0].field],
					'complete_length': echartsData[0][data.tableData[1].field],
					'userList': userArr,
				}
			},
			checkNegative,
		},
	};
</script>
<style lang="less" scoped>
	// 图表通用样式，主要有黑色loading 和 黑色 ‘没有数据’，样式名需一致
	@import '../../common/chart.less';

	.scale-container {
		position: relative;
		height: 50px;
		margin: 0px 20px;
		background-color: 'rgba(18, 125, 179, 0)';
	}

	.scale {
		position: absolute;
		top: 25px;
		/* 中间位置 */
		width: 100%;
		height: 8px;
		/* 刻度线的高度 */
		background-color: #004466;
		/* 刻度线颜色 */
		border-radius: 4px;
		/* 圆角效果 */
		z-index: 1;
		/* 保证刻度线在进度条上方 */
	}

	.progress-bar {
		position: absolute;
		top: 25px;
		/* 进度条倾斜放置位置 */
		height: 8px;
		/* 进度条高度 */
		background-color: #28a745;
		/* 绿色进度条颜色 */
		border-radius: 4px;
		/* 圆角效果 */
		z-index: 2;
		/* 确保进度条在刻度线的下方 */
	}

	.left-direction {
		left: 0;
	}

	.right-direction {
		right: 0;
	}

	.mark {
		position: absolute;
		text-align: center;
		color: #c3c3c3;
		/* 字体颜色 */
		margin-top: -22px;
		/* 数字距离刻度线的间距 */
		font-size: 12px;
		/* 字体大小 */
	}

	.tick {
		position: absolute;
		bottom: 26px;
		width: 1px;
		height: 6px;
		background-color: #c3c3c3;
		/* 刻度线颜色 */
	}

	.icon {
		position: absolute;
		top: 0px;
		/* 图标距离刻度线的间距 */
		width: 18px;
		height: 21px;
		transform: translateX(-50%);
		/* 图标居中对齐 */
		background-image: url('./images/user.png');
		z-index: 10;
	}
</style>
<style>
	/* 全局loading样式修改 */

	.chartMain .loading .el-loading-spinner .circular {
		width: 34px !important;
		height: 34px !important;
	}

	.chartMain .el-dialog__header {
		padding: 9px 20px 10px !important;
		background: #2a3352 !important;
		text-align: left;
		box-sizing: border-box;
		height: 50px;
		line-height: 32px;
	}

	.chartMain .el-dialog__title {
		text-align: left;
		/* font-size: 18px; */
		line-height: 18px !important;
		color: #b2d3fe !important;
	}

	.chartMain .el-dialog__body {
		padding: 10px 20px 30px 20px;
		background: #1a2032 !important;
		line-height: 24px;
		font-size: 14px;
	}

	.chartMain .el-dialog__headerbtn .el-dialog__close {
		color: #b2d3fe !important;
	}

	.chartMain .dialog-footer {
		text-align: right;
		margin-bottom: -14px;
		margin-right: 4px;
	}

	.chartMain .el-dialog__headerbtn {
		top: 15px;
		/* font-size: 18px; */
	}
</style>